package cn.fl.insurance.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.commons.result.ResponseData;
import cn.fl.custpay.dto.DataResultDTO;
import cn.fl.insurance.condition.InsFeeDeductRecQueryCondition;
import cn.fl.insurance.transform.InsFeeDeductRecVOTransform;
import cn.fl.preloan.IInsPlcBscInfoService;
import cn.fl.preloan.condition.InsFeeDeductQueryCondition;
import cn.fl.preloan.dto.*;
import cn.fl.preloan.dto.insurance.GetInsPlcBscInfoRequest;
import cn.fl.preloan.dto.insurance.InsPlcBscInfoDTO;
import cn.fl.preloan.enums.PreloanResultCodeEnum;
import cn.fl.preloan.insurance.IInsFeeDeductService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;

import cn.fl.insurance.constant.InsFeeDeductRecConstant;
import cn.fl.insurance.dto.InsFeeDeductRecDTO;
import cn.fl.insurance.service.IInsFeeDeductRecService;
import cn.fl.insurance.vo.InsFeeDeductRecVO;
import cn.fl.insurance.vo.InsPlcBscInfoVO;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;

import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;

import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;

/**
 * @Description: 保险违约金扣除记录表 控制层
 */
@Controller
@RequestMapping("/insurance/insFeeDeductRec")
public class InsFeeDeductRecController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(InsFeeDeductRecController.class);
	
	/**
	 * InsFeeDeductRec 服务层BEAN
	 */
	@Autowired
	private IInsFeeDeductRecService insFeeDeductRecService;
	@Autowired
	private IPrjPrdPaySchMService iPrjPrdPaySchMService;
	@Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
    private IInsPlcBscInfoService insPlcBscInfoService;
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;
	@Autowired
	private IInsFeeDeductService insFeeDeductService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载InsFeeDeductRec列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insFeeDeductRec/insFeeDeductRecList");
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载InsFeeDeductRec Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insFeeDeductRec/insFeeDeductRecModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载InsFeeDeductRec Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("insurance/insFeeDeductRec/insFeeDeductRecModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		InsFeeDeductRecVO insFeeDeductRecVO = this.insFeeDeductRecService.selectById(Long.valueOf(id));
        mav.addObject("insFeeDeductRecVO", insFeeDeductRecVO);
		return mav;
	}
	
	/**
	 * 流程中保单违约金-详情
	 */
	@RequestMapping(value = "/toInsuranceDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toInsuranceDetailPage(HttpServletRequest request,HttpServletResponse response){
		BaseLogUtils.info(logger, "toModifyPage", "加载InsFeeDeductRec Modify页面.",CurrentThreadContext.getCurrentUserName());
		String id = request.getParameter("id");//支付表ID
		if (StringUtils.isEmpty(id)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "支付表号不能为空!");
		}
		ModelAndView view = new ModelAndView("insurance/insFeeDeductRec/insuranceDetail");
		
		//查询违约金相关信息
		InsFeeDeductRecVO insFeeDeducRecVO = this.insFeeDeductRecService.selectById(Long.valueOf(id));
        Long paySchId = insFeeDeducRecVO.getPaySchId();
        Long plcId = insFeeDeducRecVO.getPlcId();
        if(paySchId != null) {
        	PrjPrdPaySchMVO iPrjPrdPaySchMVO = this.iPrjPrdPaySchMService.selectById(paySchId);
        	if (iPrjPrdPaySchMVO != null) {
        		insFeeDeducRecVO.setLsPd(iPrjPrdPaySchMVO.getLsPd());
        		insFeeDeducRecVO.setLsDt(iPrjPrdPaySchMVO.getLsDt());
        	}
        }
        //保证金处理方式
      	Map<String, String> handleWayCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsFeeDeductRecConstant.CODE_HANDLE_WAY_CD);
      	//保证金处理方式
		if(handleWayCdMap != null && handleWayCdMap.containsKey(insFeeDeducRecVO.getHandleWayCd())){
			insFeeDeducRecVO.setHandleWayNm(handleWayCdMap.get(insFeeDeducRecVO.getHandleWayCd()));
		}
		//保单性质
		Map<String, String> feeTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), InsFeeDeductRecConstant.CODE_FEE_TYP_CD);
		//费用类型(名字)
		if (feeTypCdMap != null && feeTypCdMap.containsKey(insFeeDeducRecVO.getFeeTypCd())) {
			insFeeDeducRecVO.setFeeTypNm(feeTypCdMap.get(insFeeDeducRecVO.getFeeTypCd()));
    	}
      	//保单止保时间(类型转换)
        if (insFeeDeducRecVO.getPlcEndTm() != null) {
        	insFeeDeducRecVO.setPlcEndTms(DateUtils.formatDateToString(insFeeDeducRecVO.getPlcEndTm(), DateUtils.YYYY_MM_DD));
        }
        //处理时间(类型转换)
		if (insFeeDeducRecVO.getCrtTm() != null) {
			insFeeDeducRecVO.setCrtTms(DateUtils.formatDateToString(insFeeDeducRecVO.getCrtTm(), DateUtils.YYYY_MM_DD));
		}
		//扣除金额(类型转换)
		if (insFeeDeducRecVO.getDeductAmt() != null) {
			insFeeDeducRecVO.setDeductAmts(DecimalUtils.convertFenToYuan(insFeeDeducRecVO.getDeductAmt()));
		}
		//起租日期(类型转换)
		if (insFeeDeducRecVO.getLsDt() != null) {
			insFeeDeducRecVO.setLsDts(DateUtils.formatDateToString(insFeeDeducRecVO.getLsDt(), DateUtils.YYYY_MM_DD));
		}

		//查询保单信息
		InsPlcBscInfoVO insPlcBscInfoVO = new InsPlcBscInfoVO();
		GetInsPlcBscInfoRequest getRequest = new GetInsPlcBscInfoRequest();
		getRequest.setId(plcId);
		ResponseData<InsPlcBscInfoDTO> responseData = this.insPlcBscInfoService.selectById(getRequest);
		InsPlcBscInfoVO plcBscInfoVO = new InsPlcBscInfoVO();
		if (null != responseData && ResponseData.SUCCESS_CODE.equals(responseData.getCode()) && null != responseData.getData()){
			InsPlcBscInfoDTO dto = responseData.getData();
			BeanUtils.copyProperties(dto,plcBscInfoVO);
		}
        if (insPlcBscInfoVO.getPlcBgTm() != null) {
            insPlcBscInfoVO.setPlcBgTms(DateUtils.formatDateToString(insPlcBscInfoVO.getPlcBgTm(), DateUtils.YYYY_MM_DD));
        }
        if (insPlcBscInfoVO.getPlcEndTm() != null) {
            insPlcBscInfoVO.setPlcEndTms(DateUtils.formatDateToString(insPlcBscInfoVO.getPlcEndTm(), DateUtils.YYYY_MM_DD));
        }
        if (insPlcBscInfoVO.getInsTtlFee() != null) {
            insPlcBscInfoVO.setInsTtlFeeDb(DecimalUtils.convertFenToYuan(insPlcBscInfoVO.getInsTtlFee()));
        }
        
		view.addObject("insPlcBscInfoVO", insPlcBscInfoVO);
		view.addObject("insFeeDeducRecVO",insFeeDeducRecVO);
		
		return view;
	}
	
	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

    /**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initInsFeeDeductRecList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		//设置查询条件
		InsFeeDeductQueryCondition qc = new InsFeeDeductQueryCondition();
		String cstNm = request.getParameter("cstNm");//客户名称
		String paySchNo = request.getParameter("paySchNo");//支付表号
		if (StringUtils.isNotEmpty(cstNm)) {
			qc.setCstNm(cstNm);
		}
		if (StringUtils.isNotBlank(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
        qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		page.setCondition(qc);
		List<InsFeeDeductRecVO> insFeeDeductRecVO = new ArrayList<>();
		BaseLogUtils.info(logger, "initInsFeeDeductRecList", "初始化InsFeeDeductRec列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		ResponseData<InsFeeDeductRecPageResponse> data = this.insFeeDeductService.searchListPageByCondition(page.getCurrentPage(),page.getEveryPage(),qc);
		List<InsFeeDeductDTO> list = (List<InsFeeDeductDTO>) data.getData().getInsFeeDeductRecDTOS();
		for(InsFeeDeductDTO deductDTO :list){
			InsFeeDeductRecVO ins = new InsFeeDeductRecVO();
			BeanUtils.copyProperties(deductDTO, ins);
			insFeeDeductRecVO.add(ins);
		}
		if (CollectionUtils.isNotEmpty(insFeeDeductRecVO)){
			for (InsFeeDeductRecVO vo : insFeeDeductRecVO){
				Long paySchId = vo.getPaySchId();
				PrjPrdPaySchMVO prjPrdPaySchMVO = this.iPrjPrdPaySchMService.selectById(paySchId);
				if (prjPrdPaySchMVO != null){
					vo.setLsDt(prjPrdPaySchMVO.getLsDt());
					vo.setLsPd(prjPrdPaySchMVO.getLsPd());
				}
			}
		}
		page.setTotalCount(data.getData().getTotalCount());
		ListPageVO<InsFeeDeductRecVO> listPage = new ListPageVO<InsFeeDeductRecVO>(insFeeDeductRecVO,page.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeInsFeeDeductRecByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeInsFeeDeductRecByIds", "删除InsFeeDeductRec数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			DeleteByIdsRequest req = new DeleteByIdsRequest();
			req.setIds(idsList);
			ResponseData data = this.insFeeDeductService.deleteByIds(req);
			if(!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeInsFeeDeductRecByIds", "删除InsFeeDeductRec数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeInsFeeDeductRecByIds", "删除InsFeeDeductRec数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeInsFeeDeductRecByIds", "删除InsFeeDeductRec数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeInsFeeDeductRecByIds", "删除InsFeeDeductRec数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getInsFeeDeductRecById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getInsFeeDeductRecById", "获取InsFeeDeductRec数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			GetInsFeeDeductRecRequest req= new GetInsFeeDeductRecRequest();
			req.setId(Long.valueOf(id));
			ResponseData data = this.insFeeDeductService.selectInsFeeDeductRecById(req);
			InsFeeDeductRecVO insFeeDeducRecVO = new InsFeeDeductRecVO();
			BeanUtils.copyProperties(data.getData(), insFeeDeducRecVO);
			if(null == insFeeDeducRecVO){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getInsFeeDeductRecById", "获取InsFeeDeductRec数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(insFeeDeducRecVO);
			BaseLogUtils.info(logger, "getInsFeeDeductRecById", "获取InsFeeDeductRec数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getInsFeeDeductRecById", "获取InsFeeDeductRec数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getInsFeeDeductRecById", "获取InsFeeDeductRec数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addInsFeeDeductRec(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		InsFeeDeductRecVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForInsFeeDeductRec(request);//获取参数
			AddInsDeductRecRequest req = new AddInsDeductRecRequest();
			InsFeeDeductDTO dto = new InsFeeDeductDTO();
			BeanUtils.copyProperties(entity, dto);
			req.setDto(dto);
			ResponseData data = this.insFeeDeductService.addInsDeductRec(req);
			result.setData(dto.getId());
			BaseLogUtils.info(logger, "addInsFeeDeductRec", "新增InsFeeDeductRec数据成功,ID:"+dto.getId()+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addInsFeeDeductRec", "新增InsFeeDeductRec数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addInsFeeDeductRec", "新增InsFeeDeductRec数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyInsFeeDeductRec(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		InsFeeDeductRecVO entity = null;
		try {
			entity = this.getRequestParamForInsFeeDeductRec(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyInsFeeDeductRec", "修改InsFeeDeductRec信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}
			ModifyInsFeeDeductRecRequest req = new ModifyInsFeeDeductRecRequest();
			InsFeeDeductDTO dto = new InsFeeDeductDTO();
			BeanUtils.copyProperties(entity, dto);
			req.setDto(dto);
			ResponseData data  = this.insFeeDeductService.modifyInsFeeDeductRec(req);
			if(!data.getCode().equals(PreloanResultCodeEnum.SUCCESS.getCode())){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyInsFeeDeductRec", "修改InsFeeDeductRec数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyInsFeeDeductRec", "修改InsFeeDeductRec数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyInsFeeDeductRec", "修改InsFeeDeductRec数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyInsFeeDeductRec", "修改InsFeeDeductRec数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private InsFeeDeductRecVO getRequestParamForInsFeeDeductRec(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String cstId = request.getParameter("cstId");//客户ID
		String cstNm = request.getParameter("cstNm");//客户名称
		String paySchId = request.getParameter("paySchId");//支付表ID
		String paySchNo = request.getParameter("paySchNo");//支付表号
		String paySchDId = request.getParameter("paySchDId");//PRJ_PRD_PAY_SCH_D表主键ID
		String feeTypCd = request.getParameter("feeTypCd");//费用类型(CAP0018)  02.客户保证金 11.保险保证金 
		String handleWayCd = request.getParameter("handleWayCd");//保证金处理方式（CAP0017） 1.期末退回 2.期末冲抵 3.平均冲抵 4.扣除 5.已转出 6.脱保扣除
		String deductAmt = request.getParameter("deductAmt");//转出金额（分）
		String deductDt = request.getParameter("deductDt");//转出时间
		String deductRem = request.getParameter("deductRem");//备注
		String plcId = request.getParameter("plcId");//保单ID
		String deductStsCd = request.getParameter("deductStsCd");//状态:1. 已扣除 2.转正常中  3.已转正常
		String plcEndTm = request.getParameter("plcEndTm");//保单止保时间
		String plcPropCd = request.getParameter("plcPropCd");//保单性质INS0003：1首年保单2续保保单

		//验证参数并赋值
		InsFeeDeductRecVO entity = new InsFeeDeductRecVO();
 		//entity.setCstId(cstId);//客户ID
 		//entity.setCstNm(cstNm);//客户名称
 		//entity.setPaySchId(paySchId);//支付表ID
 		//entity.setPaySchNo(paySchNo);//支付表号
 		//entity.setPaySchDId(paySchDId);//PRJ_PRD_PAY_SCH_D表主键ID
 		//entity.setFeeTypCd(feeTypCd);//费用类型(CAP0018)  02.客户保证金 11.保险保证金 
 		//entity.setHandleWayCd(handleWayCd);//保证金处理方式（CAP0017） 1.期末退回 2.期末冲抵 3.平均冲抵 4.扣除 5.已转出 6.脱保扣除
 		//entity.setDeductAmt(deductAmt);//转出金额（分）
 		//entity.setDeductDt(deductDt);//转出时间
 		//entity.setDeductRem(deductRem);//备注
 		//entity.setPlcId(plcId);//保单ID
 		//entity.setDeductStsCd(deductStsCd);//状态:1. 已扣除 2.转正常中  3.已转正常
 		//entity.setPlcEndTm(plcEndTm);//保单止保时间
 		//entity.setPlcPropCd(plcPropCd);//保单性质INS0003：1首年保单2续保保单
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
	
	 /**
     * 发起流程
     */
	@RequestMapping(value = "/addFlowStart.do", method = {RequestMethod.POST})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "流程发起成功");
		String insFeeDeductRecId = request.getParameter("InsFeeDeductRecId");
		InsFeeDeductRecQueryCondition insFeeDeductRecQueryQC = new InsFeeDeductRecQueryCondition();
		try {
			insFeeDeductRecQueryQC.setId(Long.valueOf(insFeeDeductRecId));
			
			//判断该保险违约金是否再结清流程中
			InsFeeDeductRecVO insFeeDeductRecVO = this.insFeeDeductRecService.selectById(Long.valueOf(insFeeDeductRecId));
			if (insFeeDeductRecVO != null) {
				PrjPrdDtlQueryCondition qc = new PrjPrdDtlQueryCondition();
				qc.setPaySchId(insFeeDeductRecVO.getPaySchId());
				List<PrjPrdDtlVO> list = this.prjPrdDtlService.selectList(qc);
				if (CollectionUtils.isNotEmpty(list)) {
					for (PrjPrdDtlVO vo : list){
						String prjPrdStsCd = vo.getPrdStsCd();
						if (prjPrdStsCd.equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_02) && prjPrdStsCd.equals(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD_04)) {
							throw new BaseException(SysLogConstant.LOG_CMM_SYS_ERROR,"该信息已在结清申请中，不可转正常申请!");
						}
					}
				}
			}
			
			result = this.insFeeDeductRecService.addRenewApply(insFeeDeductRecQueryQC);
			BaseLogUtils.info(logger, "addFlowStart", "发起转正常流程成功," + ".DATA:" + JSONObject.toJSONString(insFeeDeductRecId), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result = new DataResultVO();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "addFlowStart", "发起转正常流程失败.DATA:" + JSONObject.toJSONString(insFeeDeductRecId) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result = new DataResultVO();
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addFlowStart", "发起转正常流程失败,系统错误.DATA:" + JSONObject.toJSONString(insFeeDeductRecId) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
		
		return result;
	}
}

